<script lang="ts" setup>
import { getMap, usePopup } from '@/map';
import { RandomPointCoordinates } from '@/utils'
import { Feature, Map } from 'ol'
import { Point } from 'ol/geom'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import { Style, Circle as CircleStyle, Fill, Stroke } from 'ol/style'
import { unref } from 'vue';
import { toRaw } from 'vue';
import { Ref, onUnmounted, nextTick, reactive } from 'vue'
const map = getMap()?.map as Ref<Map>
const pointData = reactive({
    mapx: '',
    mapy: '',

})
const create = () => {
    return RandomPointCoordinates({ size: 12 }).map((item) => new Feature({
        geometry: new Point(item),
    }))
}
const pointLayer = new VectorLayer({
    source: new VectorSource({
        wrapX: false,
        features: create()
    }),
    style: new Style({
        image: new CircleStyle({
            radius: 6, // 散点的半径
            fill: new Fill({
                color: 'green' // 散点的填充颜色
            }),
            stroke: new Stroke({
                color: 'green', // 散点的边框颜色
                width: 2 // 散点的边框宽度
            })
        })
    }),
    properties: {
        name: "dfs"
    }
})

const { overlay } = usePopup({
    map: map as any,
    element: 'custom_popup',
    selectListener(event) {
        const selected = event.selected
        if (!selected || selected.length < 1) {
            overlay.setPosition(undefined)
            return;
        }
        const point = selected[0].getGeometry() as Point
        const coordinates = point.getCoordinates()
        pointData.mapx = coordinates[0].toString()
        pointData.mapy = coordinates[1].toString()
        overlay.setPosition(coordinates)
    }
})

nextTick(() => {
    map.value?.addLayer(pointLayer)
})
onUnmounted(() => {
    toRaw(unref(map)).removeLayer(pointLayer)
    pointLayer.getSource()?.clear()
})

</script>
<template>
    <div class="container">
        <div id="custom_popup" class="ol-popup">
            <n-form  :model="pointData" label-placement="left" label-width="auto"
                require-mark-placement="right-hanging">
                <div class="form_title">要素信息</div>
                <n-form-item label="X:" path="mapx">
                    <n-input v-model:value="pointData.mapx" disabled type="text" placeholder="基本的 Input" />
                </n-form-item>
                <n-form-item label="Y:" path="mapy">
                    <n-input v-model:value="pointData.mapy" disabled type="text" placeholder="基本的 Input" />
                </n-form-item>
            </n-form>
        </div>
        <div>
            弹窗
        </div>
    </div>
</template>
<style scoped>
.container {

}

.ol-popup {
    --color: rgba(0, 255, 255, 0.5);
    background-color: var(--color);
    border: 1px solid var(--color);
    border-radius: 10px;
    padding: 10px;
}
</style>